package com.luoluo.view;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.tools.struts.StrutsLinkTool;

/**
 * 链接工具
 * 
 * @author luoluo
 */
public class LinkTool extends StrutsLinkTool {

	/**
	 * URL编码
	 * 
	 * @param url
	 * @return
	 */
	public static String encode_url(String url) {
		return encode_url(url, "utf-8");
	}

	/**
	 * URL编码
	 * 
	 * @param url
	 * @param charset
	 * @return
	 */
	public static String encode_url(String url, String charset) {
		if (StringUtils.isEmpty(url))
			return "";
		try {
			return URLEncoder.encode(url, charset);
		} catch (UnsupportedEncodingException e) {
		}
		return null;
	}

	public static String decode_url(String url, String charset) {
		if (StringUtils.isEmpty(url))
			return "";
		try {
			return URLDecoder.decode(url, charset);
		} catch (UnsupportedEncodingException e) {
		}
		return null;
	}

	/**
	 * URL编码
	 * 
	 * @param url
	 * @return
	 */
	public static String decode_url(String url) {
		return decode_url(url, "utf-8");
	}

	/**
	 * 获取浏览器提交的整形参数
	 * 
	 * @param param
	 * @param defaultValue
	 * @return
	 */
	public int param(String param, int defaultValue) {
		String val = request.getParameter(param);
		try {
			return Integer.parseInt(val);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 获取浏览器提交的长整形参数
	 * 
	 * @param param
	 * @param defaultValue
	 * @return
	 */
	public long lparam(String param, long defaultValue) {
		String val = request.getParameter(param);
		try {
			return Long.parseLong(val);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public long[] lparams(String param) {
		String[] val = request.getParameterValues(param);
		try {
			long[] longs = new long[val.length];
			for (int i = 0; i < val.length; i++) {
				longs[i] = Long.parseLong(val[i]);
			}
			return longs;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取浏览器提交的字符串参数
	 * 
	 * @param param
	 * @param defaultValue
	 * @return
	 */
	public String param(String param, String defaultValue) {
		String val = request.getParameter(param);
		return null != val ? decode_url(val) : defaultValue;
	}

	public String param(String param) {
		return decode_url(request.getParameter(param));
	}
}
